package edu.sctu.yueding.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import edu.sctu.yueding.R;
import edu.sctu.yueding.activitys.ActivityDetailsActivity;
import edu.sctu.yueding.activitys.LoginActivity;
import edu.sctu.yueding.activitys.MainActivity;
import edu.sctu.yueding.activitys.SettingsActivity;
import edu.sctu.yueding.bean.Comments;
import edu.sctu.yueding.bean.Files;
import edu.sctu.yueding.bean.Tweets;
import edu.sctu.yueding.config.CacheConfig;
import edu.sctu.yueding.config.URLConfig;
import edu.sctu.yueding.utils.DateUtils;
import edu.sctu.yueding.utils.JumpUtils;
import edu.sctu.yueding.utils.L;
import edu.sctu.yueding.utils.httputils.GetVolleyHttp;
import edu.sctu.yueding.utils.httputils.SharePreference;
import edu.sctu.yueding.view.NoSlideListView;
import edu.sctu.yueding.view.MyGridView;


/**
 * Created by Administrator on 2016/8/4.
 */
public class CommunityListViewAdapter extends BaseAdapter {

    private Activity activity;
    private ViewHolder viewHolder;
    private List<Tweets> data;
    private View view;
    private Map<String, String> mData = new HashMap<>();// 存储的EditText值
    private int pos;
    private Integer index = -1;
    private SharePreference sharePreference;
    private String token = "";

    private HashMap<Integer, List<Comments>> noMultiplexing;//解决复用问题
    private HashMap<Integer, CommunityContentListViewAdapter> listViewAdapterMap;//解决复用问题

    private HashMap<Integer, List<Files>> noMultiplexing2;//解决复用问题
    private HashMap<Integer, CommunityItemGridViewAdapter> gridViewAdapterMap;//解决复用问题

    private HashMap<Integer, TextView> zanTextMap = new HashMap<>();
    private HashMap<Integer, EditText> commentEditMap = new HashMap<>();

    private long userId;


    private boolean isAddAll = true;

    private String mShareTitle, mShareContent, mUrl, mShareImageUrl;

    /**
     * 评论
     */
    private String commentContent = "";
    private HashMap<String, String> commentMap;
    private List<Comments> comments = new ArrayList<>();

    /**
     * 构造方法
     *
     * @param activity
     * @param data
     */
    public CommunityListViewAdapter(Activity activity, List<Tweets> data) {
        this.data = data;
        this.activity = activity;
        sharePreference = SharePreference.getInstance(activity);
        token = sharePreference.getString(CacheConfig.CACHE_TOKEN);
        userId = sharePreference.getLong(CacheConfig.CACHE_USER_ID);
        noMultiplexing();
        initAdapter();
    }


    private void noMultiplexing() {
        noMultiplexing = new HashMap<>();
        noMultiplexing2 = new HashMap<>();
        for (int i = 0; i < data.size(); i++) {
            noMultiplexing.put(i, data.get(i).getComments());
            noMultiplexing2.put(i, data.get(i).getFiles());
        }
    }

    private void initAdapter() {
        listViewAdapterMap = new HashMap<>();
        gridViewAdapterMap = new HashMap<>();
        for (int i = 0; i < data.size(); i++) {
            listViewAdapterMap.put(i, new CommunityContentListViewAdapter(noMultiplexing.get(i), activity));
            gridViewAdapterMap.put(i, new CommunityItemGridViewAdapter(activity,
                    noMultiplexing2.get(i),
                    3)
            );
        }
    }


    /**
     * 刷新数据
     *
     * @param data
     */
    public void fresh(List<Tweets> data, boolean isAddAll) {
        if (isAddAll) {
            this.data.addAll(data);
        } else {
            this.data = data;

        }
        noMultiplexing();
        initAdapter();
        for (int i = 0; i < gridViewAdapterMap.size(); i++) {
            gridViewAdapterMap.get(i).notifyDataSetChanged();
        }
        notifyDataSetChanged();
    }


    @Override
    public int getCount() {
        if (data != null && data.size() > 0) {
            return data.size();
        } else {
            return 0;
        }
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            view = LayoutInflater.from(activity).inflate(R.layout.item_community_list, null);
            viewHolder = new ViewHolder();

            viewHolder.usernameText = (TextView) view.findViewById(R.id.item_community_list_username);
            viewHolder.mHeadImg = (ImageView) view.findViewById(R.id.item_community_list_headimg);
            viewHolder.gridView = (MyGridView) view.findViewById(R.id.community_list_gridView);
            viewHolder.contentText = (TextView) view.findViewById(R.id.community_list_content);
            viewHolder.listView = (NoSlideListView) view.findViewById(R.id.community_content_list_view);
            viewHolder.editText = (EditText) view.findViewById(R.id.community_edit_text);
            viewHolder.zanTxt = (TextView) view.findViewById(R.id.community_zan_txt);
            viewHolder.dateTime = (TextView) view.findViewById(R.id.item_community_list_date_time);
            viewHolder.mShareImg = (ImageView) view.findViewById(R.id.community_share_img);
            viewHolder.deleteText = (TextView) view.findViewById(R.id.item_community_list_delete);

            viewHolder.editText.setTag(position);
            viewHolder.listView.setTag(position);
            viewHolder.mHeadImg.setTag(position);
            view.setTag(viewHolder);//将viewHolder储存在view中
            zanTextMap.put(position, viewHolder.zanTxt);
            commentEditMap.put(position, viewHolder.editText);

        } else {
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
            viewHolder.editText.setTag(position);
            viewHolder.mHeadImg.setTag(position);
            viewHolder.listView.setTag(position);
            zanTextMap.put(position, viewHolder.zanTxt);
            commentEditMap.put(position, viewHolder.editText);
        }

        viewHolder.mHeadImg.setImageResource(R.drawable.user_default_portrait);

        if ((Integer) viewHolder.mHeadImg.getTag() == position && data.get(position).getAuthorURL() != null && !data.get(position).getAuthorURL().equals("")) {

            GetVolleyHttp.getInstance(activity).setImageLoader(viewHolder.mHeadImg,
                    R.drawable.user_default_portrait,
                    R.drawable.user_default_portrait,
                    data.get(position).getAuthorURL());
        }


        viewHolder.dateTime.setText(DateUtils.getStrTime(String.valueOf(data.get(position).getCreateDate())));

        zanTextMap.get(position).setText(data.get(position).getPraiseNum() + "");

        viewHolder.usernameText.setText(data.get(position).getAuthorName());
        viewHolder.contentText.setText(data.get(position).getContent());

        /**
         * 删除
         */

        if (userId == data.get(position).getAuthorId()) {
            viewHolder.deleteText.setVisibility(View.VISIBLE);
            viewHolder.deleteText.setClickable(true);
            viewHolder.deleteText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    viewHolder.deleteText.setClickable(false);

                    new AlertDialog.Builder(activity).setTitle("确认删除")
                            .setIcon(android.R.drawable.ic_dialog_info)
                            .setPositiveButton("是", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    pos = position;
                                    deleteOne();
                                }
                            })
                            .setNegativeButton("否", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // 点击“返回”后的操作,这里不设置没有任何操作
                                }
                            }).show();
                }
            });
        } else {
            viewHolder.deleteText.setVisibility(View.GONE);
            viewHolder.deleteText.setClickable(false);
        }


        viewHolder.listView.setAdapter(listViewAdapterMap.get(position));

        commentEditMap.get(position).setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(activity.getCurrentFocus().getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    pos = position;
                    commentContent = mData.get(position + "");

                    if (commentContent != null && !commentContent.equals("")) {
                        commentMap = new HashMap<>();
                        commentMap.put("content", commentContent);
                        commentMap.put("threadId", data.get(position).getCommentUUID());
                        commentMap.put("parentId", "-1");
                        commentEditMap.get(position).setText("");
                        GetVolleyHttp.getInstance(activity).getStringPOSTJsonData(URLConfig.URL_COMMUNITY_COMMENT,
                                commentMap, listenerComment, errorListener, URLConfig.BEAREAR + token);
                    } else {
                        Toast.makeText(activity, "评论不能为空", Toast.LENGTH_SHORT).show();

                    }

                }
                return false;
            }
        });

        viewHolder.zanTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (SharePreference.getInstance(activity).ifHaveShare(CacheConfig.CACHE_TOKEN)) {
                    pos = position;
                    zan(position);
                } else {
                    Toast.makeText(activity, "请先登录", Toast.LENGTH_SHORT).show();
                }

            }
        });

        viewHolder.mShareImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new ShareAction(activity).setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                        .withTitle("yueding")
                        .withText("yueding")
                        .withMedia(new UMImage(activity, "http://118.178.86.71:8080/yueding-admin/logo.png"))
                        .withTargetUrl(URLConfig.URL_COMMUNITY_SHARE(data.get(position).getId()))
                        .setCallback(umShareListener)
                        .open();
            }
        });


        editTextUtils(position);
//
//        if (data.get(position).getFiles() != null && data.get(position).getFiles().size() > 0) {
//
        if (data.get(position).getFiles().size() == 1) {
            viewHolder.gridView.setNumColumns(1);
        }else {
            viewHolder.gridView.setNumColumns(3);
        }
//        setNumColumns(data.get(position).getFiles().size());


//            viewHolder.gridView.setMinimumHeight(ScreenUntils.getScreenWidth(activity) / viewHolder.gridView.getNumColumns());

        viewHolder.gridView.setAdapter(gridViewAdapterMap.get(position));
//        }
        return view;
    }


    /**
     * 点赞
     *
     * @param pos
     */
    private void zan(int pos) {
        HashMap<String, String> map = new HashMap<>();
        GetVolleyHttp.getInstance(activity).getStringPOSTJsonData(URLConfig.getZanURL(data.get(pos).getId()),
                map,
                listener,
                errorListener, URLConfig.BEAREAR + token);
    }

    /**
     * 点赞 listener
     */
    Response.Listener<String> listener = new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d("zan", response);
            com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(response);
            String zanNumber = jsonObject.getString("data");
            zanTextMap.get(pos).setText(zanNumber);

        }
    };

    /**
     * 评论 listener
     */
    Response.Listener<String> listenerComment = new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            comment(response);
        }
    };

    /**
     * 评论
     *
     * @param response
     */
    private void comment(String response) {
        Log.d("response", response);
        comments = data.get(pos).getComments();
        Comments comment = new Comments();
        comment.setAuthor_id(-1);
        comment.setAuthorName(sharePreference.getString(CacheConfig.CACHE_NICKNMAE));
        comment.setContent(commentContent);
        comment.setParent_id(-1);
        comment.setThread_id(data.get(pos).getCommentUUID());
        comments.add(comment);

        listViewAdapterMap.get(pos).onDataChange(comments);
        commentContent = "";

    }


    /**
     * 删除一个
     *
     * @param
     */
    private void deleteOne() {

        GetVolleyHttp.getInstance(activity).getStringDELETEJsonData(URLConfig.URL_COMMUNITY_DELETE(data.get(pos).getId()),
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        data.remove(pos);
                        L.d("delete", "ssssss");
                        fresh(data, false);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        L.d("delete", "ffffffff");
                    }
                },
                URLConfig.BEAREAR + token);

    }


    static class ViewHolder {
        TextView usernameText, dateTime, deleteText;
        ImageView mHeadImg, mShareImg;
        ListView listView;
        EditText editText;
        TextView contentText, zanTxt;
        MyGridView gridView;
    }

    /**
     * 处理 editText错位
     *
     * @param position
     */
    private void editTextUtils(int position) {
        viewHolder.editText.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    index = (Integer) v.getTag();
                }
                return false;
            }
        });
        if (index == position) {
            viewHolder.editText.setText(mData.get(position));
        } else {
            viewHolder.editText.setText("");
        }

        viewHolder.editText.addTextChangedListener(new MyTextWatcher(viewHolder));
    }

    class MyTextWatcher implements TextWatcher {
        public MyTextWatcher(ViewHolder holder) {
            mHolder = holder;
        }

        private ViewHolder mHolder;

        @Override
        public void onTextChanged(CharSequence s, int start,
                                  int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start,
                                      int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s != null && !"".equals(s.toString())) {
                int position = (Integer) mHolder.editText.getTag();
                mData.put(position + "",
                        s.toString());// 当EditText数据发生改变的时候存到data变量中

            }
        }
    }

    Response.ErrorListener errorListener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
            Log.d("s", "sss");
        }
    };

    private void setNumColumns(int number) {
        switch (number) {
            case 1:
                viewHolder.gridView.setNumColumns(1);
                break;
            case 2:
                viewHolder.gridView.setNumColumns(2);
                break;
            case 3:
                viewHolder.gridView.setNumColumns(3);
                break;
            case 4:
                viewHolder.gridView.setNumColumns(2);
                break;
            default:
                viewHolder.gridView.setNumColumns(3);
                break;
        }
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {
            com.umeng.socialize.utils.Log.d("plat", "platform" + platform);
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toast.makeText(activity, platform + " 收藏成功啦", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(activity, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(activity, platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
                com.umeng.socialize.utils.Log.d("throw", "throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(activity, platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };
}
